package db;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Booking {

	public static int buyTickets(int line, String userid, int nums) {
		Calendar c = Calendar.getInstance();
		c.setTimeInMillis(new Date().getTime());
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		String now = dateFormat.format(c.getTime());

		String sql = "insert into booked(flight_id,passenger,make_order,price) values("

				+ line
				+ ",'"
				+ userid
				+ "','"
				+ now
				+ "',"
				+ " (SELECT PRICE FROM flights WHERE id="
				+ line
				+ " limit 0,1)*if("
				+ nums
				+ ">=(select min_buy  from flights where id="
				+ line
				+ " )  and "
				+ " (select min_buy  from flights where id="
				+ line
				+ " limit 0,1 )>0 ,"
				+ " 1-(SELECT max_discount FROM flights WHERE id="
				+ line
				+ " limit 0,1)/100,1)+"
				+ "(select tax from cities where id="
				+ "(select origin from flights where id="
				+ line
				+ " limit 0,1)" + "limit 0,1)" + ")";
		System.out.println(sql);
		int sucess = 0;
		try {

			int r;
			for (int i = 0; i < nums; i++)

			{
				r = DataBaseManager.getConnection().createStatement()
						.executeUpdate(sql);

				if (r == 1)
					sucess++;
			}
			sql="update flights set sold=sold+"+sucess+" where id="+line;
			r = DataBaseManager.getConnection().createStatement().executeUpdate(sql);
			return sucess;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sucess;

	}

	public static void main(String[] args) {

	}
}
